﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Threading;
using System.Windows.Threading;
using System.IO;
using System.Windows.Media;

namespace Indigo.Quibbler.Common
{
    public partial class AsyncImageControl : UserControl
    {

        ManualResetEvent _threadRunning = new ManualResetEvent(true);

        #region Properties
        public string Source
        {
            get { return (string)GetValue(ImageUrlProperty); }
            set { SetValue(ImageUrlProperty, value); }
        }

        public static readonly DependencyProperty ImageUrlProperty =
            DependencyProperty.Register("Source", typeof(string), typeof(AsyncImageControl), new UIPropertyMetadata(string.Empty, OnImageUrlChanged));


        public ImageSource LoadingImage
        {
            get { return (ImageSource)GetValue(LoadingImageProperty); }
            set { SetValue(LoadingImageProperty, value); }
        }
        public static readonly DependencyProperty LoadingImageProperty =
            DependencyProperty.Register("LoadingImage", typeof(ImageSource), typeof(AsyncImageControl),
            new UIPropertyMetadata(new BitmapImage(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/Image-Loading.png", UriKind.RelativeOrAbsolute))));


        public ImageSource ErrorImage
        {
            get { return (ImageSource)GetValue(ErrorImageProperty); }
            set { SetValue(ErrorImageProperty, value); }
        }
        public static readonly DependencyProperty ErrorImageProperty =
            DependencyProperty.Register("ErrorImage", typeof(ImageSource), typeof(AsyncImageControl),
            new UIPropertyMetadata(new BitmapImage(new Uri("pack://application:,,/Quibbler - Universal News Reader;component/Images/NA.png", UriKind.RelativeOrAbsolute))));


        #endregion

        public AsyncImageControl()
        {
            InitializeComponent();
        }

        private static void OnImageUrlChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as AsyncImageControl).OnImageUrlChanged(e);
        }

        private void OnImageUrlChanged(DependencyPropertyChangedEventArgs e)
        {
            try
            {
                string url = (string)e.NewValue;
                if (url != null && url != string.Empty)
                {

                    Thread _thread = new Thread(new ParameterizedThreadStart(_DownloadImage));
                    _thread.Start(url);
                }
            }
            catch (Exception ex)
            {
                _Init();
            }
        }

        private void _DownloadImage(object url)
        {
            try
            {
                this.Dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)delegate
                {
                    imageControl.Source = this.LoadingImage;
                });
                _threadRunning.WaitOne();
                _threadRunning.Reset();
                Downloader.Downloader instance = new Indigo.Quibbler.Downloader.Downloader();
                instance.DataStorePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Universal News Reader\DataStore\Library\Pub\Images\");
                string localPath = instance.GetLocalPath((string)url, string.Empty);

                this.Dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)delegate
                {
                    if (this.Source == (string)url)
                        imageControl.Source = new BitmapImage(new Uri(localPath, UriKind.RelativeOrAbsolute));
                });

                _threadRunning.Set();
            }
            catch
            {
                _threadRunning.Set();
                this.Dispatcher.Invoke(DispatcherPriority.Background, (ThreadStart)delegate
                {
                    imageControl.Source = this.ErrorImage;
                });
            }
        }


        private void _Init()
        {
        }

    }
}
